package com.demo.nio;

import com.demo.test.Server;
import com.objectplanet.image.PngEncoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @ClassName SendScreenImg
 * @Description 该类实时发送截屏
 */
public class SendScreen extends Thread {
    public static int SERVERPORT = 8000;
    public ServerSocket serverSocket;
    private Robot robot;
    public Dimension screen;
    public Rectangle rect;
    public long startTime, endTime, s1, e1;
    public Socket socket;
    private boolean socketFlag = true;
    private PngEncoder pngEncoder = new PngEncoder();
    private ExecutorService executorService;


    public static void main(String[] args) {
        new SendScreen(SERVERPORT).start();
    }

    public SendScreen(int SERVERPORT) {
        try {
            // 初始化服务 绑定接口
            this.serverSocket = new ServerSocket(SERVERPORT);
            this.serverSocket.setSoTimeout(864000000);

            //创建一个线程池
            executorService = Executors.newFixedThreadPool(100);

            // 创建robot用于截图
            robot = new Robot();
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 获取屏幕大小
        screen = Toolkit.getDefaultToolkit().getScreenSize();
        rect = new Rectangle(screen);
    }

    @Override
    public void run() {
        startTime = System.currentTimeMillis();
        try {
            System.out.println("等待数据传输...");
            socket = serverSocket.accept();

            Runnable runnable = () -> {
                try {
                    // 创建压缩流对象
                    DataOutputStream out = new DataOutputStream(socket.getOutputStream());
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

                    while (socketFlag) {
                        // 获取屏幕图片
                        BufferedImage img = robot.createScreenCapture(rect);
                        s1 = System.currentTimeMillis();
                        ImageIO.write(img, "png", byteArrayOutputStream);
                        e1 = System.currentTimeMillis();
                        System.out.println("Server Write: " + (e1 - s1));

                        // 图片写入
                        out.write(byteArrayOutputStream.toByteArray());
                        out.flush();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            };
            executorService.submit(runnable);
        } catch (IOException ioe) {
            System.out.println("连接断开");
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("共享发送错误.");
                }
            }
        }
        endTime = System.currentTimeMillis();
        System.out.println("发送延时: " + (endTime - startTime) + " ms");
    }

    public void close() throws IOException {
        socketFlag = false;
        if (socket != null) socket.close();
        serverSocket.close();
    }
}

// 连接处理
class getConn implements Runnable {
    private ServerSocket serverSocket;

    public getConn(ServerSocket serverSocket) {
        this.serverSocket = serverSocket;
    }

    @Override
    public void run() {
        try {
            while (true) {
                Socket socket = serverSocket.accept();
                System.out.println(socket.getInetAddress().getHostAddress() + "连接成功");
                new Thread(new sendImg(socket)).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

// 发送图片
class sendImg implements Runnable {
    private Socket socket;
    long s1, e1;

    public sendImg(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        try {
            Robot robot = new Robot();
            // 获取屏幕大小
            Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
            Rectangle rect = new Rectangle(screen);

            DataOutputStream out = new DataOutputStream(socket.getOutputStream());
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            // 获取屏幕图片
            BufferedImage img = robot.createScreenCapture(rect);
            s1 = System.currentTimeMillis();
            ImageIO.write(img, "png", byteArrayOutputStream);
            e1 = System.currentTimeMillis();
            System.out.println("Server Write: " + (e1 - s1));
            out.write(byteArrayOutputStream.toByteArray());

            socket.shutdownOutput();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}